<script>
import { mapGetters } from 'vuex'
import { hireType, excelZhHeaderEnum } from '@/constant'
import PageTools from '@/components/PageTools/PageTools.vue'
import Avatar from '@/components/Avatar/Avatar.vue'
import CopyRight from '@/components/CopyRight/CopyRight.vue'
import AddEmpDialog from '@/views/employees/components/addEmpDialog/addEmpDialog.vue'
import UploadDialog from '@/views/employees/components/uploadDialog/uploadDialog.vue'
import roleDialog from '@/views/employees/components/ roleDialog/roleDialog.vue'

export default {
  name: 'employees',
  data() {
    return {
      /* 聘用形式的枚举对象 */
      hireType,
      /* 员工默认头像 */
      defaultImage: require('@/assets/images/bigUserHeader.png'),
      /* 分页参数 */
      pageParams: { page: 1, size: 10 },
      /* 获取员工列表的loading状态 */
      loading: false,
      /* 是否显示添加员工的对话框 */
      showEmpDialog: false,
      /* 是否显示导入excel的对话框 */
      showUploadDialog: false,
      /* 是否显示角色对话框 */
      showRoleDialog: false
    }
  },
  methods: {
    /* 派发action发送请求获取员工列表的回调函数 */
    async fetchEmployessList() {
      try {
        this.loading = true
        await this.$store.dispatch('employeesStore/fetchEmployessList', this.pageParams)
      } catch (error) {
        this.$message.error(error.message)
      } finally {
        this.loading = false
      }
    },
    /* 分页器一页展示的数据条数发生变化的回调函数 */
    handleSizeChange(size) {
      this.pageParams.size = size
      this.fetchEmployessList()
    },
    /* 分页器当前页发生变化的回调函数 */
    handleCurrentChange(page) {
      this.pageParams.page = page
      this.fetchEmployessList()
    },
    /* 点击查看员工按钮的回调函数 */
    handleShowEmployees(employee) {
      this.$router.push({ name: 'detail', params: { id: employee.id } })
    },

    /* 点击分配角色按钮的回调函数 */
    async handleAssignRoles(employees) {
      // 使用ref获取子组件的实例调用子组件的fetchRoleList()发送请求获取所有角色列表
      await this.$refs.roleDialog.fetchRoleList()
      // 使用ref获取子组件的实例调用子组件的findRoleIds(员工的ID)发送请求获取当前员工的角色ID数组
      await this.$refs.roleDialog.findRoleIds(employees.id)
      // 打开对话框
      this.showRoleDialog = true
    },
    /* 点击删除员工按钮的回调函数 */
    async handleDeleteEmployees(employee) {
      try {
        const confirm = await this.$confirm(`删除${employee.username}, 是否继续?`, '提示', { type: 'warning' }).catch(error => error)
        if (confirm === 'cancel') return
        const message = await this.$store.dispatch('employeesStore/deleteEmployess', employee.id)
        this.$message.success(message)
        if (this.employessList.length <= 1) this.pageParams.page--
        this.fetchEmployessList()
      } catch (error) {
        this.$message.error(error.message)
      }
    },
    /* 点击添加员工按钮的回调函数 */
    handleAddEmployees() {
      this.showEmpDialog = true
    },
    /* 处理聘用形式的回调函数 */
    handleFormOfEmployment(type) {
      return hireType[type] || '未知'
    },
    /* 添加员工对话框组件添加员工成功的自定义事件 */
    addEmpSuccess() {
      this.showEmpDialog = false
      this.showUploadDialog = false
      this.fetchEmployessList()
    },
    /* 点击导入excel按钮的回调函数 */
    importExcel() {
      this.showUploadDialog = true
    },
    /* 点击导出excel按钮的回调函数 */
    async exportExcel() {
      const confirm = await this.$confirm('导出excel, 是否继续?', '提示', { type: 'warning' }).catch(error => error)
      if (confirm === 'cancel') return
      // 默认拿到数组第一个对象的键(属性名)
      const header = Object.keys(this.employessList[0]).map(item => excelZhHeaderEnum[item])
      // 将员工列表转换为二维数组
      const data = this.employessList.map(item => Object.values(item))
      // 引入exportExcel第三方库
      const excel = await import('@/vendor/exportExcel')
      // 下载excel文件
      excel.export_json_to_excel({
        header, // 表头（数组格式）
        data, // 数据（二维数组）[['陶品奇', 'web前端']]
        filename: '员工表格', // 导出的文件名称
        autoWidth: true, // 是否自适应宽度
        bookType: 'xlsx' // 文件后缀名
      })
    }
  },
  mounted() {
    this.fetchEmployessList()
  },
  computed: {
    ...mapGetters('employeesStore', ['employessList', 'total']),
    toolsTitle() {
      return `总共${this.total}位员工`
    }
  },
  components: {
    UploadDialog,
    AddEmpDialog,
    CopyRight,
    Avatar,
    PageTools,
    roleDialog
  }
}
</script>

<template>
  <div class="employees">
    <el-card>
      <page-tools :title="toolsTitle">
        <el-button type="primary" icon="el-icon-plus" @click="handleAddEmployees">添加员工</el-button>
        <el-button type="success" icon="el-icon-download" @click="importExcel">导入excel</el-button>
        <el-button type="info" icon="el-icon-upload2" @click="exportExcel">导出excel</el-button>
      </page-tools>
    </el-card>
    <el-card>
      <el-table :data="employessList" border stripe v-loading="loading" element-loading-text="拼命加载中" element-loading-spinner="el-icon-loading" element-loading-background="rgb(255, 255, 255">
        <el-table-column type="index" label="序号" align="center" width="80px"></el-table-column>
        <el-table-column prop="username" label="姓名" align="center" width="100px"></el-table-column>
        <el-table-column label="头像" align="center" width="150px">
          <template #default="{row}">
            <Avatar :src="row.staffPhoto" :default-image="defaultImage" :size="50"></Avatar>
          </template>
        </el-table-column>
        <el-table-column prop="mobile" label="手机" align="center" width="200px"></el-table-column>
        <el-table-column prop="workNumber" label="工号" align="center" width="200px" sortable></el-table-column>
        <el-table-column label="聘用形式" align="center" width="200px">
          <template #default="{row}">
            <el-link type="primary" :underline="false">{{ handleFormOfEmployment(row.formOfEmployment) }}</el-link>
          </template>
        </el-table-column>
        <el-table-column prop="departmentName" label="部门" align="center" width="200px"></el-table-column>
        <el-table-column prop="timeOfEntry" label="入职时间" align="center" width="200px" sortable></el-table-column>
        <el-table-column prop="correctionTime" label="转正时间" align="center" width="200px" sortable></el-table-column>
        <el-table-column label="账户状态" align="center" width="200px">
          <template #default="{row}">
            <el-switch v-model.number="row.enableState" :active-value="1" :inactive-value="0"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template #default="{row}">
            <el-button type="success" icon="el-icon-position" @click="handleAssignRoles(row)">分配角色</el-button>
            <el-button type="primary" icon="el-icon-view" @click="handleShowEmployees(row)">查看员工</el-button>
            <el-button type="danger" icon="el-icon-delete" @click="handleDeleteEmployees(row)">删除员工</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pageParams.page"
        :page-sizes="[10, 20, 30, 40]"
        :page-size="pageParams.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        background
      >
      </el-pagination>
    </el-card>
    <copy-right></copy-right>
    <add-emp-dialog :show-emp-dialog.sync="showEmpDialog" @submit="addEmpSuccess"></add-emp-dialog>
    <upload-dialog :showUploadDialog.sync="showUploadDialog" @submit="addEmpSuccess"></upload-dialog>

    <!--角色的对话框-->
    <role-dialog :show-role-dialog.sync="showRoleDialog" ref="roleDialog" append-to-body></role-dialog>
  </div>
</template>

<style scoped lang="scss">
.employees {
  .el-card {
    margin-top: 20px;
  }

  .el-table {
    margin-bottom: 15px;
  }

  .el-pagination {
    text-align: center;
  }
}
</style>
